package com.libinshen.wxpay.login.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.libinshen.wxpay.common.enums.AccountType;
import com.libinshen.wxpay.common.util.common.DateUtils;
import com.libinshen.wxpay.common.util.common.MD5Util;
import com.libinshen.wxpay.login.entity.Account;
import com.libinshen.wxpay.login.mapper.AccountMapper;
import com.libinshen.wxpay.login.service.AccountService;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.UUID;

@Service
public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> implements AccountService {

    @Override
    public boolean createAccount(String username, String password) {
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String md5Password = MD5Util.MD5(password + uuid);
        Account account = Account.builder()
                .username(username)
                .password(md5Password)
                .salt(uuid)
                .status(AccountType.NORMAL.getType())
                .createTime(DateUtils.getDateMonth())
                .updateTime(DateUtils.getDateMonth())
                .build();
        return this.save(account);
    }

    @Override
    public Account getAccountByUsername(final String username) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("username", username);
        return this.getOne(queryWrapper);
    }

    @Override
    public boolean verification(String username, String password) {
        Account account = getAccountByUsername(username);
        String newSaltPassword = MD5Util.MD5(password + account.getSalt());
        if (Objects.equals(newSaltPassword, account.getPassword())) {
            return true;
        }
        return false;
    }
}
